﻿using Leo.Awesome.AppPlatform.Domain;
using Leo.Awesome.AppPlatform.Dtos;
using Leo.Awesome.AppPlatform.Enums;
using Leo.Awesome.AppPlatform.Repostories;
using Leo.Awesome.AppPlatform.Services;
using Leo.Core.Application;
using Leo.Core.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Authorization.Permissions;
using Volo.Abp.Identity;
using Volo.Abp.PermissionManagement;
using Volo.Abp.Users;

namespace Leo.Awesome.AppPlatform.Servcies
{
    public class PermissionMenuAppService : BaseApplicationService, IPermissionMenuAppService
    {
        private readonly IdentityUserManager _identityUserManager;
        private readonly ICurrentUser currentUser;
        private readonly IPermissionAppService _permissionAppService;
        private readonly IMenuRepository _menuRepository;

        public PermissionMenuAppService(IdentityUserManager identityUserManager, 
            ICurrentUser currentUser,
            IPermissionAppService permissionAppService,
            IMenuRepository mainRepository)
        {
            _identityUserManager = identityUserManager;
            this.currentUser = currentUser;
            _permissionAppService = permissionAppService;
            this._menuRepository = mainRepository;
        }
        public async Task<List<MenuTreeOutput>> GetMenusForCurrentUser()
        {
            var user = await _identityUserManager.FindByIdAsync(currentUser.GetId().ToString());
            CheckBussionErrors(user == null, "该用户不存在或已被删除,无法获取当前用户菜单,");
            CheckBussionErrors(user.IsActive == false, "该用户已被禁用,无法获取当前用户菜单,");
            var permissionsGroups = await _permissionAppService.GetAsync(UserPermissionValueProvider.ProviderName, currentUser.GetId().ToString());

            var permissionGrantInfoDtos = new List<PermissionGrantInfoDto>();
            foreach (var item in permissionsGroups.Groups)
            {
                permissionGrantInfoDtos.AddRange(item.Permissions);
            }

            var allMenuItems = (await _menuRepository.GetListAsync(x => x.Display))
                .OrderBy(x => x.Order).ToList();

            // 根据授权权限过滤菜单项
            var permissionNames = permissionGrantInfoDtos
                .Where(x => x.IsGranted).Select(x => x.Name).ToList();

            var filteredMenuItems = allMenuItems.Where(x =>
            permissionNames.Contains(x.Permission) && (x.MenuType == MenuType.Button
            || x.MenuType == MenuType.MenuItem) && x.Display)
                                                .ToList();

            var reversedStrs = new List<Guid>();
            foreach (var item in filteredMenuItems)
            {
                if (item.PathCode.IsNullOrWhiteSpace())
                {
                    continue;
                }
                var parts = item.PathCode.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

                var guidList = parts
                     .Select(x => Guid.TryParse(x, out Guid guid) ? guid : Guid.Empty)
                     .ToList();
                reversedStrs.AddRange(guidList);
            }
            var menus = allMenuItems.Where(x => reversedStrs.Contains(x.Id)).ToList();
            var outputs = ObjectMapper.Map<List<Menu>, List<MenuTreeOutput>>(menus);
            return outputs.ToTree(x => x.Id, x => x.ParentId).ToList();
        }
    }
}
